// pages/Networks/NetworkList.tsx
import React, { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Plus, Play, Square, Trash2, Network, Globe } from 'lucide-react';
import { useNetworkStore } from '../../stores/networkStore';
import { useApp } from '../../App';
import { ROUTES } from '../../router';
import type { NetworkSummary } from '../../types/api';

const NetworkList: React.FC = () => {
  const navigate = useNavigate();
  const { currentConnection } = useApp();
  const {
    networks,
    loading,
    error,
    fetchNetworks,
    startNetwork,
    stopNetwork,
    deleteNetwork
  } = useNetworkStore();

  useEffect(() => {
    if (currentConnection) {
      fetchNetworks(currentConnection);
    }
  }, [currentConnection, fetchNetworks]);

  const handleStartNetwork = async (networkName: string) => {
    if (!currentConnection) return;
    try {
      await startNetwork(currentConnection, networkName);
    } catch (error) {
      console.error('Failed to start network:', error);
    }
  };

  const handleStopNetwork = async (networkName: string) => {
    if (!currentConnection) return;
    try {
      await stopNetwork(currentConnection, networkName);
    } catch (error) {
      console.error('Failed to stop network:', error);
    }
  };

  const handleDeleteNetwork = async (networkName: string) => {
    if (!currentConnection) return;
    if (window.confirm(`Are you sure you want to delete network "${networkName}"?`)) {
      try {
        await deleteNetwork(currentConnection, networkName);
      } catch (error) {
        console.error('Failed to delete network:', error);
      }
    }
  };

  const getNetworkStatus = (active: boolean) => {
    if (active) {
      return { color: 'text-green-500', bgColor: 'bg-green-500/10', label: 'Active' };
    } else {
      return { color: 'text-red-500', bgColor: 'bg-red-500/10', label: 'Inactive' };
    }
  };

  if (!currentConnection) {
    return (
      <div className="text-center py-12">
        <p className="text-lg text-gray-400 mb-4">No connection selected</p>
        <button
          onClick={() => navigate(ROUTES.CONNECTIONS)}
          className="px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-lg transition-colors"
        >
          Go to Connections
        </button>
      </div>
    );
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-purple-500"></div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="text-center py-8">
        <p className="text-red-500 mb-4">{error}</p>
        <button
          onClick={() => fetchNetworks(currentConnection)}
          className="px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-lg transition-colors"
        >
          Retry
        </button>
      </div>
    );
  }

  return (
    <div>
      <div className="flex justify-between items-center mb-6">
        <h2 className="text-2xl font-bold">Virtual Networks</h2>
        <button
          onClick={() => navigate(ROUTES.NETWORK_NEW)}
          className="flex items-center gap-2 px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-lg transition-colors"
        >
          <Plus size={16} />
          New Network
        </button>
      </div>

      {networks.length === 0 ? (
        <div className="text-center py-12">
          <Globe className="mx-auto mb-4 text-gray-400" size={48} />
          <p className="text-lg text-gray-400 mb-4">No virtual networks found</p>
          <button
            onClick={() => navigate(ROUTES.NETWORK_NEW)}
            className="px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-lg transition-colors"
          >
            Create Network
          </button>
        </div>
      ) : (
        <div className="grid gap-4">
          {networks.map((network: NetworkSummary) => {
            const status = getNetworkStatus(network.active);

            return (
              <div
                key={network.name}
                className="p-4 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 hover:shadow-lg transition-all"
              >
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-4">
                    <div className="flex items-center gap-2">
                      <Network size={20} className="text-blue-500" />
                      <div>
                        <h3 className="font-semibold">{network.name}</h3>
                        <p className="text-sm text-gray-500">{network.uuid}</p>
                      </div>
                    </div>
                    <div className="flex items-center gap-2">
                      <span className={`px-2 py-1 text-xs rounded ${status.bgColor} ${status.color}`}>
                        {status.label}
                      </span>
                      {network.bridge && (
                        <span className="px-2 py-1 text-xs bg-gray-500/10 text-gray-500 rounded">
                          Bridge: {network.bridge}
                        </span>
                      )}
                    </div>
                  </div>

                  <div className="flex items-center gap-2">
                    {network.active ? (
                      <button
                        onClick={() => handleStopNetwork(network.name)}
                        className="p-2 text-yellow-500 hover:bg-yellow-500/10 rounded transition-colors"
                        title="Stop Network"
                      >
                        <Square size={16} />
                      </button>
                    ) : (
                      <button
                        onClick={() => handleStartNetwork(network.name)}
                        className="p-2 text-green-500 hover:bg-green-500/10 rounded transition-colors"
                        title="Start Network"
                      >
                        <Play size={16} />
                      </button>
                    )}

                    <button
                      onClick={() => navigate(ROUTES.NETWORK_EDIT(network.name))}
                      className="p-2 text-blue-500 hover:bg-blue-500/10 rounded transition-colors"
                      title="Edit Network"
                    >
                      <Network size={16} />
                    </button>

                    <button
                      onClick={() => handleDeleteNetwork(network.name)}
                      className="p-2 text-red-500 hover:bg-red-500/10 rounded transition-colors"
                      title="Delete Network"
                    >
                      <Trash2 size={16} />
                    </button>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
};

export default NetworkList;